/*
 * @(#)MaintDmsCheckoutAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.quartz.Scheduler;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsContent;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsDocumentIndex;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.core.DmsContentManager;
import com.dcivision.dms.core.DmsDocumentNameConvertor;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.UnrelockableException;
import com.dcivision.dms.core.VersionControlManager;
import com.dcivision.dms.dao.DmsContentDAObject;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsDocumentIndexDAObject;
import com.dcivision.dms.dao.DmsVersionDAObject;
import com.dcivision.dms.dao.MtmDocumentVersionDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SchedulerFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.WorkflowActionFormInterface;
import com.dcivision.framework.web.WorkflowActionInterface;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.bean.WorkflowRecord;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.core.SystemWorkflowConstant;
import com.dcivision.workflow.core.WorkflowProgressManager;
import com.dcivision.workflow.dao.WorkflowRecordDAObject;
import com.dcivision.workflow.web.MaintWorkflowRecordForm;


/**
  MaintDmsCheckoutAction.java
  This class is for maint dms checkout / checkin action
    @author          Zoe Shum
    @company         DCIVision Limited
    @creation date   17/08/2003
    @version         $Revision: 1.92.2.7 $
 */

public class MaintDmsCheckoutAction extends com.dcivision.setup.web.AbstractMaintPermissionAction implements com.dcivision.framework.web.WorkflowActionInterface {

  public static final String REVISION = "$Revision: 1.92.2.7 $";

  protected static String MESSAGE_RECORD_CHECK_IN = "dms.message.records_checked_in";
  protected static String MESSAGE_RECORD_CHECK_OUT = "dms.message.records_checked_out";

  private String odmaProcess = "";
  
  public MaintDmsCheckoutAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  
  public String getMajorDAOClassName() {
    return ("com.dcivision.dms.dao.DmsCheckoutHistoryDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  
  public String getFunctionCode() {
    return (null);
  }


  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    MaintDmsVersionForm versionForm = (MaintDmsVersionForm)form;
    
    //if this is odma process    
    odmaProcess = request.getParameter("odmaProcess");
    //if request form odma ,some field is store at xml,so parse xml field to form first    
    try{
        if ("odma".equals(odmaProcess)||"paraScan".equals(odmaProcess)){
            parseFormXmlDataToForm(versionForm);
        }
    }catch (Exception e){
      log.error(e, e);
    }

    String opMode = versionForm.getOpMode();
    String navMode=versionForm.getNavMode();
    String directPage=versionForm.getDirectPage();

    String directURL=versionForm.getDirectURL();
    
    //For checkin action in the ViewDmsCompoundDocument.jsp page
    if("true".equals(request.getParameter("selfCheckout"))&&!DmsOperationConstant.CHECKOUT_CHECK.equals(opMode)){
      versionForm.setReturnTo(request.getParameter("returnTop"));
      request.setAttribute("returnTo",versionForm.getReturnTo());
    }

    Log logger = new LogFactoryImpl().getInstance(this.getClass());
    java.util.Date triggerTime = null;
    org.quartz.SimpleTrigger trigger = null;
    int val = 0;
    java.sql.Timestamp src= null;
    
    //In compound Document page when checkIn action need this parameter
    request.setAttribute("ID",versionForm.getDocumentID());
    request.setAttribute("rootID", versionForm.getRootID());
    request.setAttribute("parentID", versionForm.getParentID());
    request.setAttribute("navMode",GlobalConstant.NAV_MODE_VIEW);
    
    String docID=null;
    if(!Utility.isEmpty(directURL) && directURL.indexOf("navMode=P")>0){
      if(!DmsOperationConstant.CHECKOUT_OPERATION.equals(opMode)){
        navMode=GlobalConstant.NAV_MODE_PREVIEW; 
      }
      if(directURL.indexOf("objectID=")>0){
        docID=directURL.substring(directURL.indexOf("objectID=")+1,directURL.length());
        docID=docID.substring(8,docID.indexOf("&"));
        
      }
      request.setAttribute("directURL",directURL);
    }
    /*
     * joan.xiong update code for bug EIP-862 by 2006/11/02
     */
//    if (!DmsOperationConstant.CHECKOUT_CHECK.equals(opMode)&&!Utility.isEmpty((String)request.getParameter("returnTop"))) {
    if (!DmsOperationConstant.CHECKOUT_CHECK.equals(opMode)&&!Utility.isEmpty(request.getParameter("returnTop")) && Utility.isEmpty(versionForm.getReturnTo())) {
    /*
     * joan.xiong update code end
     */
      versionForm.setReturnTo(request.getParameter("returnTop"));
    }
 

    String documentID = versionForm.getDocumentID();
    if(!Utility.isEmpty(navMode) && navMode.equals(GlobalConstant.NAV_MODE_PREVIEW)){
        if(!Utility.isEmpty(docID)){
          documentID = docID; 
        }
      }else{
        if (DmsOperationConstant.CREATE_COMPOUND_DOCUMENT_VIEW.equals(directPage)){
          documentID = versionForm.getDocumentID();
        }
      }
 
    // Set function code if necessary.
    if (!Utility.isEmpty(versionForm.getCurFunctionCode())) {
      this.setFunctionCode(versionForm.getCurFunctionCode());
    }

    String sCurFunctionCode = versionForm.getCurFunctionCode();
    log.debug("opMode="+opMode+", navMode="+navMode + ", directPage = " + directPage);

    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }
    //Used to disable the header and footer when display the document summary page
    if (GlobalConstant.NAV_MODE_PREVIEW.equals(navMode)){
      request.setAttribute("SHOW_HEADER_FOOTER", "N");
    }
    String returnTo = versionForm.getReturnTo();
    if( !Utility.isEmpty(returnTo) && returnTo.indexOf("/dms")>=0) {
      int start = returnTo.indexOf("/dms") ;
      returnTo = returnTo.substring(start);
    }
    if (opMode != null) {
      if (DmsOperationConstant.CHECKIN_OPERATION.equals(opMode)) {
        log.debug("enter check_In");
        if (!this.isTokenValid(request,true)){
          
          this.saveToken(request);
          if (!Utility.isEmpty(versionForm.getReturnTo()) && !versionForm.getReturnTo().equals("null") && !versionForm.getReturnTo().equals("undefined")){//Update By Jim Zhou      EIP-1591      2007/01/22
            ActionForward actionForward = new ActionForward();
            actionForward.setPath(returnTo);
            return actionForward;
          } else if (!Utility.isEmpty(versionForm.getDirectPage())){
            return mapping.findForward(versionForm.getDirectPage());
          } else {
            return mapping.findForward("Home");
          }
        }
        try {
          this.checkInRecord(mapping, versionForm, request, response);
          this.handleWorkflowRoutine(mapping, versionForm, request, response, opMode, navMode);
          this.commit(request);
          addMessage(request, MESSAGE_RECORD_CHECK_IN);
        } catch (ApplicationException appEx) {
            this.rollback(request);
            /*
             * joan.xiong update code for bug EIP-161 by 2006/09/18
             */
            //handleApplicationException(request, appEx);
            try{
            	handleApplicationException(request, appEx);
            }catch(Exception e){}
            /*
             * joan.xiong update code end
             */
        }
        if (isError(request)) {
          // for odma return  
          saveToken(request);
          if ("odma".equals(odmaProcess)){
            request.setAttribute("odmaGetType","checkin" );
            request.setAttribute("result","faild" );
            request.setAttribute("inforCode","ERROR_CHECKIN_01" );            
            request.setAttribute("documentID",versionForm.getDocumentID());
            return mapping.findForward("DMS.ODMA_RESULT");
          }else{ 
            versionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
            return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
          }
        }
        else {
          versionForm.setOpMode(GlobalConstant.NAV_MODE_LIST);
          request.setAttribute("documentID", versionForm.getDocumentID());
          //joan.xiong add code for bug EIP-1119 by 2006/12/01
          if(directPage.equals("DMS.LSEARCH")){
        	  request.setAttribute("searchCheckIn","true");
          }//joan.xiong add code end
          
          // for odma return   
          if ("odma".equals(odmaProcess)){
            request.setAttribute("odmaGetType","checkin" );
            request.setAttribute("result","success" );
            request.setAttribute("inforCode","MESSAGE_CHECKIN_01" );              
            request.setAttribute("documentID",versionForm.getDocumentID());
            return mapping.findForward("DMS.ODMA_RESULT");
          }else{
            if("true".equals(request.getSession().getAttribute("fromEmail"))){
              if(!Utility.isEmpty(docID)){
                request.setAttribute("documentID",docID); 
              }
              return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
            }
            if(!Utility.isEmpty(navMode) && navMode.equals(GlobalConstant.NAV_MODE_PREVIEW)){
              if(!Utility.isEmpty(docID)){
                request.setAttribute("documentID",docID); 
              }
              return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
            }else{
              if (DmsOperationConstant.CREATE_COMPOUND_DOCUMENT_VIEW.equals(directPage)){
                request.setAttribute("documentID",versionForm.getParentID());
                versionForm.setOpMode(GlobalConstant.NAV_MODE_REFRESH);
              }
              return mapping.findForward(directPage);
            }
          }
        }
      } //Checkin minor mode
      else if (DmsOperationConstant.CHECKIN_MINOR.equals(opMode)) {
        log.debug("enter checkIn minor");
        if (!this.isTokenValid(request,true)){
          
          this.saveToken(request);
          if (!Utility.isEmpty(versionForm.getReturnTo()) && !versionForm.getReturnTo().equals("null") && !versionForm.getReturnTo().equals("undefined")){//Update By Jim Zhou      EIP-1591      2007/01/22
            ActionForward actionForward = new ActionForward();
            actionForward.setPath(returnTo);
            return actionForward;
          } else if (!Utility.isEmpty(versionForm.getDirectPage())){
            return mapping.findForward(versionForm.getDirectPage());
          } else {
            return mapping.findForward("Home");
          }
        }
        try {
          this.minorCheckInRecord(mapping, versionForm, request, response);
          this.handleWorkflowRoutine(mapping, versionForm, request, response, opMode, navMode);
          this.commit(request);
          addMessage(request, MESSAGE_RECORD_CHECK_IN);
        } catch (ApplicationException appEx) {
            this.rollback(request);
            saveToken(request);
            /*
             * joan.xiong update code for bug EIP-161 by 2006/11/02
             */
            //handleApplicationException(request, appEx);
            try{
            	handleApplicationException(request, appEx);
            }catch(Exception e){}
            /*
             * joan.xiong update code end
             */
        }
        if (isError(request)) {
          // for odma return   
          if ("odma".equals(odmaProcess)){
            request.setAttribute("odmaGetType","checkin" );
            request.setAttribute("result","faild" );
            request.setAttribute("inforCode","ERROR_CHECKIN_01" );            
            request.setAttribute("documentID",versionForm.getDocumentID());

            return mapping.findForward("DMS.ODMA_RESULT");
          }else{            
            versionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);

            return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
          }  
        }
        else {
          versionForm.setOpMode(GlobalConstant.NAV_MODE_LIST);
          request.setAttribute("documentID", versionForm.getDocumentID());
          //joan.xiong add code for bug EIP-1119 by 2006/12/01
          if(directPage.equals("DMS.LSEARCH")){
        	  request.setAttribute("searchCheckIn","true");
          }//joan.xiong add code end
          // for odma return   
          if ("odma".equals(odmaProcess)){
            request.setAttribute("odmaGetType","checkin" );
            request.setAttribute("result","success" );
            request.setAttribute("inforCode","MESSAGE_CHECKIN_01" );              
            request.setAttribute("documentID",versionForm.getDocumentID());
            return mapping.findForward("DMS.ODMA_RESULT");
          }else{          
            if("true".equals(request.getSession().getAttribute("fromEmail"))){
              if(!Utility.isEmpty(docID)){
                request.setAttribute("documentID",docID); 
              }
              return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
            }
            if(!Utility.isEmpty(navMode) && navMode.equals(GlobalConstant.NAV_MODE_PREVIEW)){
              if(!Utility.isEmpty(docID)){
                request.setAttribute("documentID",docID); 
              }
              return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
            } else {
              if (DmsOperationConstant.CREATE_COMPOUND_DOCUMENT_VIEW.equals(directPage)){
                request.setAttribute("documentID",versionForm.getParentID());
                versionForm.setOpMode(GlobalConstant.NAV_MODE_REFRESH);
              }
              this.saveToken(request);
              return mapping.findForward(directPage);
            }
          }
        }

      } //No Update Check In
      else if (DmsOperationConstant.NO_UPDATE_CHECKIN.equals(opMode)) {
        log.debug("enter no update checkin ");
        if (!this.isTokenValid(request,true)){
          
          this.saveToken(request);
          if (!Utility.isEmpty(versionForm.getReturnTo()) && !versionForm.getReturnTo().equals("null") && !versionForm.getReturnTo().equals("undefined")){//Update By Jim Zhou      EIP-1591      2007/01/22
            ActionForward actionForward = new ActionForward();
            actionForward.setPath(returnTo);
            return actionForward;
          } else if (!Utility.isEmpty(versionForm.getDirectPage())){
            return mapping.findForward(directPage);
          } else {
            return mapping.findForward("Home");
          }
        }
        try {
          this.NoUpdateCheckInRecord(mapping, versionForm, request, response);
          this.handleWorkflowRoutine(mapping, versionForm, request, response, opMode, navMode);
          this.commit(request);
          addMessage(request, MESSAGE_RECORD_CHECK_IN);
        } catch (ApplicationException appEx) {
            this.rollback(request);
            handleApplicationException(request, appEx);
        }
        if (isError(request)) {
          // for odma return   
          if ("odma".equals(odmaProcess)){
            request.setAttribute("odmaGetType","checkin" );
            request.setAttribute("result","faild" );
            request.setAttribute("inforCode","ERROR_CHECKIN_01" );            
            request.setAttribute("documentID",versionForm.getDocumentID());
            return mapping.findForward("DMS.ODMA_RESULT");
          }else{            
            versionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
            return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
          }            
        }
        else {
          versionForm.setOpMode(GlobalConstant.NAV_MODE_LIST);
          request.setAttribute("documentID", versionForm.getDocumentID());
          //joan.xiong add code for bug EIP-1119 by 2006/12/01
          if(directPage.equals("DMS.LSEARCH")){
        	  request.setAttribute("searchCheckIn","true");
          }//joan.xiong add code end
          // for odma return   
          if ("odma".equals(odmaProcess)){
            request.setAttribute("odmaGetType","checkin" );
            request.setAttribute("result","success" );
            request.setAttribute("inforCode","MESSAGE_CHECKIN_01" );            
            request.setAttribute("documentID",versionForm.getDocumentID());
            return mapping.findForward("DMS.ODMA_RESULT");
          }else{
            if("true".equals(request.getSession().getAttribute("fromEmail"))){
              if(!Utility.isEmpty(docID)){
                request.setAttribute("documentID",docID); 
              }
              return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
            }
            if(!Utility.isEmpty(navMode) && navMode.equals(GlobalConstant.NAV_MODE_PREVIEW)){
              if(!Utility.isEmpty(docID)){
                request.setAttribute("documentID",docID); 
              }
              return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
            }else{
              return mapping.findForward(directPage);
            }
          }  
        }

      } //Check out operation
      else if (DmsOperationConstant.CHECKOUT_OPERATION.equals(opMode)) {
        log.debug("enter checkOut = navMode = "+navMode);
        
        SessionContainer sessionContainer = this.getSessionContainer(request);
        Connection conn = this.getConnection(request);
        DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
        DmsDocument dmsDocument =docRetrievalManager.getDocument(TextUtility.parseIntegerObj(documentID));
        try {          
        	// add code by beyond
        	//checkout document must check doucment item status is active 
        	if(GlobalConstant.STATUS_LOCKED.equals( dmsDocument.getItemStatus())){
        		// duplicate checkout	
        		throw new UnrelockableException(DmsErrorConstant.DUPLICATE_FILE_CHECKOUT);        	
        	}
          
        	//if DMS_CHECKOUT_EXPIRE_DAY>0 then perform then check in Scheduler
        	if(TextUtility.parseInteger(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_CHECKOUT_EXPIRE_DAY)) > 0){
        		
        		val = TextUtility.parseInteger(SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_CHECKOUT_EXPIRE_DAY));
        		src= Utility.getCurrentTimestamp();
        		triggerTime =Utility.addDay(src,val);
        		//triggerTime =Utility.addMinute(src,val);	
        		
        		org.quartz.Scheduler sched = com.dcivision.framework.SchedulerFactory.getScheduler(); 
        		
        		org.quartz.JobDataMap dataMap = new org.quartz.JobDataMap();
        		dataMap.put("documentID", documentID);
        		dataMap.put("userID", TextUtility.formatIntegerObj(sessionContainer.getUserRecordID()));
        		
        		org.quartz.JobDetail job = new org.quartz.JobDetail(
        				"checkout expiry time " + new java.util.Date(),
        				"CHECKOUT_JOBGROUP"+Math.random(),
        				com.dcivision.dms.core.DmsCheckoutExpiryTime.class);
        		job.setJobDataMap(dataMap);
        		
        		logger.info("******** Schedule date: " + triggerTime.toString());
        		trigger = new org.quartz.SimpleTrigger("CheckInExpirt_"+documentID,"CHECKIN_GROUP"+Math.random(),triggerTime, null,0,0);
        		
        		trigger.setMisfireInstruction(org.quartz.SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
        		logger.info("******** Trigger created");
        		logger.info(job.getFullName() + " will run at: " + trigger.getNextFireTime() + " & repeat: " + trigger.getRepeatCount() + "/" + trigger.getRepeatInterval());
        		
        		java.util.Date ft = sched.scheduleJob(job, trigger);
        		sched = null;
        		//this.scheduledJobVec.clear();
        	}
        	
        	this.checkOutRecord(mapping, versionForm, request, response);
        	this.commit(request);
        	addMessage(request, MESSAGE_RECORD_CHECK_OUT);
        } catch (ApplicationException appEx) {
        	this.rollback(request);
        	/*
        	 * joan.xiong update code for bug EIP-674 by 2006/10/18
        	 */
//        	handleApplicationException(request, appEx);
        	try{
            	handleApplicationException(request, appEx);
        	}catch(Exception e){}
        	/*
        	 * joan.xiong update code end
        	 */
        }catch (Exception e) {
        	logger.error("Error in Scheduler.", e);
        	throw new ApplicationException(ErrorConstant.SYS_SCHEDULER_ERROR);
        }

        
        if(!Utility.isEmpty(docID)){
          request.setAttribute("documentID",docID); 
        }
        if(!Utility.isEmpty(navMode) && navMode.equals(GlobalConstant.NAV_MODE_PREVIEW)){
          request.setAttribute("SUCCESS_CHECKOUT", "true"); // used to cater the dowonload directly after checkout in summary page
          return mapping.findForward(GlobalConstant.NAV_MODE_PREVIEW);
        }else{
          if (isError(request)) {
            versionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
            if(DmsOperationConstant.LIST_SEARCH.equals(directPage)||DmsOperationConstant.LIST_KEYWORD_SEARCH.equals(directPage)||DmsOperationConstant.LIST_BULK_SEARCH.equals(directPage)||DmsOperationConstant.LIST_PERSONAL_HOME.equals(directPage)){
                return mapping.findForward(directPage);
                /*
                 * joan.xiong update code for bug EIP-674 by 2006/10/18
                 */
            }else if(DmsOperationConstant.LIST_PERSONAL_HOME.equals(versionForm.getCurFunctionCode())){
              	return mapping.findForward(versionForm.getCurFunctionCode());
              	/*
              	 * joan.xiong update code end
              	 */
            }else{
              return mapping.findForward(DmsOperationConstant.FORWARD_WITH_REQUEST);
            }
          }
          else {
            request.setAttribute("SUCCESS_CHECKOUT", "true");  //used to cater the download directly after checkout
            versionForm.setOpMode(GlobalConstant.NAV_MODE_LIST);
            return mapping.findForward(directPage);
          }
        }


      } //Display the Check-in page after validation
      else if (DmsOperationConstant.CHECKOUT_CHECK.equals(opMode)) {
        log.debug("enter checkIn page validation ");
        try {
          this.checkinStatusCheck(mapping, versionForm, request, response);

        } catch (ApplicationException appEx) {
            this.rollback(request);
            handleApplicationException(request, appEx);
        }
        if (isError(request)) {
          versionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          this.saveToken(request);
          return mapping.findForward(navMode);
        }
        this.saveToken(request);
        //versionForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);  //comment by zoe; no need set navmode since forwarding directly
        return mapping.findForward(GlobalConstant.NAV_MODE_EDIT);
      }else if ("DMS.CLIPBOARD.CHECK_OUT".equals(opMode)) {
        log.debug("enter checkIn page validation ");
        try {
          this.checkinStatusCheck(mapping, versionForm, request, response);

        } catch (ApplicationException appEx) {
            this.rollback(request);
            handleApplicationException(request, appEx);
        }
        if (isError(request)) {
          versionForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          this.saveToken(request);
          return mapping.findForward(navMode);
        }
        this.saveToken(request);
        //versionForm.setNavMode(GlobalConstant.NAV_MODE_EDIT);  //comment by zoe; no need set navmode since forwarding directly
        return mapping.findForward("DMS.CLIPBOARD.CHECK_OUT");
      }
      else {
        this.saveToken(request);
        return mapping.findForward(DmsOperationConstant.FORWARD_WITH_REQUEST);
      }
    } // Else Case when opMode = null
    else {
      return super.execute(mapping, form, request, response);
    }
  }

  public void checkInRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

    InputStream inputStream = null;
    FormFile formFile = null;
    String realDocumentName = "";

    MaintDmsVersionForm versionForm = (MaintDmsVersionForm)form;
    String rootID = versionForm.getRootID();
    String parentID = versionForm.getParentID();
    request.setAttribute("rootID",rootID);
    request.setAttribute("parentID",parentID);
    //Integer documentID = new Integer(versionForm.getDocumentID());
    Integer documentID = request.getParameter("documentID") == null ? TextUtility.parseIntegerObj(versionForm.getDocumentID()) :
                         TextUtility.parseIntegerObj(request.getParameter("documentID"));
    String checkinType = versionForm.getCheckinType();
    DmsVersion version = (DmsVersion)versionForm.getFormData();

    // set default to zero as parent for linear versioning
    version.setParentID(new Integer(0));
    try {
      // check whether check in with update
      if (!DmsOperationConstant.NO_UPDATE_CHECKIN.equals(checkinType)) {
        formFile = versionForm.getUploadFile();
        realDocumentName = formFile.getFileName();
        inputStream = formFile.getInputStream();
        version.setItemSize(new Integer(formFile.getFileSize()));
        version.setDocumentID(documentID);
        if(!"odma".equals(odmaProcess)){// odma's file name is set at parseFormXmlDataToForm() already
          version.setCheckinFileName(formFile.getFileName());
        }
      }
    } catch (IOException ioe) {
      log.error(ioe, ioe);
    }

    /*- TODO add by harry for handling for Workflow */
    /*log.debug("have Workflow:????" + versionForm.getSubmitSystemWorkflow());
         if (versionForm.getSubmitSystemWorkflow() != null) {
      version.setRecordStatus(GlobalConstant.STATUS_PENDING);
         } else {
      version.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
         }
     */
    String sCurFunctionCode = docRetrievalManager.getCurFunctionCode(docRetrievalManager.getDocument(documentID));
     
    if (SystemFunctionConstant.DMS_PUBLIC_FOLDER.equals(sCurFunctionCode)) { 
      if (sessionContainer.getAppContainer().isLightVersion() && checkExistingVersion(version,request,form)){
        deleteOldVersion(version.getDocumentID(),request,form);
      }
    }
    VersionControlManager versionControlManager = new VersionControlManager(sessionContainer, conn);
    DmsVersion newVersion = null;
    newVersion = versionControlManager.checkinDocumentName(true, checkinType, documentID, version, inputStream, realDocumentName);
    this.deleteCheckinJob(documentID);
    request.setAttribute("documentID", documentID.toString());
    
    /*- setting the ID for Workflow if any */
    if (newVersion != null) {
      versionForm.setID(newVersion.getID().toString());
    }

    try {
      sessionContainer = null;
      versionControlManager.release();
      docOperationManager.release();
      docRetrievalManager.release();
    } catch (Exception e) {
      log.error(e, e);
    } finally {
      conn = null;
    }
  }
  
  /**
   * Check does the new updated version pass the limitation on Light Version
   * @param newVersion
   * @param request
   * @param form
   * @return
   * @throws ApplicationException
  */
  public boolean checkExistingVersion(DmsVersion newVersion,HttpServletRequest request,AbstractActionForm form) throws ApplicationException{
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MaintDmsVersionForm versionForm = (MaintDmsVersionForm)form;
    Integer documentID = request.getParameter("documentID") == null ? TextUtility.parseIntegerObj(versionForm.getDocumentID()) :
                         TextUtility.parseIntegerObj(request.getParameter("documentID"));  	
    DmsVersionDAObject dmsVersionDAOject = new DmsVersionDAObject(sessionContainer,conn);
    List list = dmsVersionDAOject.getVersionsListByDocumentID(documentID,"desc"); 
    if(list.size()>1){
      return true;
    }
    try {
      sessionContainer = null;
    } catch (Exception e) {
      log.error(e, e);
    } finally {
    
    }
    return true;
  }
  
  /**
    * Delete the oldest Version (ver no.1) and shift the version status on the updatedVersion (ver no.2)
    * @param documentID
    * @param request
    * @param form
    * @throws ApplicationException
  */
  public void deleteOldVersion(Integer documentID,HttpServletRequest request,AbstractActionForm form)throws ApplicationException{
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MaintDmsVersionForm versionForm = (MaintDmsVersionForm)form;
    documentID = request.getParameter("documentID") == null ? TextUtility.parseIntegerObj(versionForm.getDocumentID()) :TextUtility.parseIntegerObj(request.getParameter("documentID"));
    DmsContentDAObject dmsContentDAO = new DmsContentDAObject(sessionContainer, conn);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DmsDocument dmsDocument =docRetrievalManager.getDocument(documentID);
    DmsVersionDAObject dmsVersionDAOject = new DmsVersionDAObject(sessionContainer,conn);
    MtmDocumentVersionDAObject mtmDocumentVersionDAOject = new MtmDocumentVersionDAObject(sessionContainer,conn);
    DmsContentManager dmsContentManager = new DmsContentManager(sessionContainer, conn);      
    List list = dmsVersionDAOject.getVersionsListByDocumentID(documentID,"desc");
    DmsVersion oldVersion=new DmsVersion();
    DmsDocumentNameConvertor documentNameConvertor = null;
    DmsVersion ver=new DmsVersion();
    
    
    //  Update the version information 
    String conName="";
    if(list.size()>=2){
      //for(int i=0;i<list.size();i++){
        //if("CURRENT".equals(ver.getVersionLabel())){
          ver=(DmsVersion)list.get(0);
          ver.setVersionLabel("ROOT");
          ver.setVersionNumber("1");
          DmsVersion version=(DmsVersion)dmsVersionDAOject.updateObject(ver);
          list.remove(ver);
        //}
      //}
      for(int i=0;i<list.size();i++){
        oldVersion=(DmsVersion)list.get(i);
        //Hard Delete the record in MTM_DOCUMENT_VERSION 
        mtmDocumentVersionDAOject.deleteObjectByID(oldVersion.getID());

        //Hard Delete the physical file 
        if (!DmsDocument.FOLDER_TYPE.equals(dmsDocument.getDocumentType())){

          DmsContent tmpContent = docRetrievalManager.getContentByContentID(oldVersion.getContentID());          
          dmsContentManager.deleteDmsDocumentStoreContent(dmsDocument,tmpContent);
            
            //Hard Delete the DmsContent record in DMS_CONTENT
            dmsContentDAO.hardDeleteByID(tmpContent.getID());
            //Hard Delete the DmsVersion record in DMS_VERSION
            dmsVersionDAOject.hardDeleteByID(oldVersion);
        }
      }
      try {
        documentNameConvertor = (DmsDocumentNameConvertor) Class.forName(
        SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_NAME_CONVERTOR_CLASS)).newInstance();
      }catch (Exception e) {
          log.error("Name Convertor class not found.", e);
          throw new ApplicationException(DmsErrorConstant.NAME_CONVERTOR_CLASS_NOT_FOUND);
       }
      docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
      dmsContentDAO = new DmsContentDAObject(sessionContainer, conn);

      //for (int i=0; i<list.size(); i++){
      DmsDocument document=docRetrievalManager.getDocument(ver.getDocumentID());
      DmsContent dmsContent=(DmsContent)dmsContentDAO.getObjectByID(ver.getContentID());    
      if (ver!=null) {
        document.setVersionNumber(ver.getVersionNumber());
        log.debug("version number = " + ver.getVersionNumber());
        String newConvertedName = documentNameConvertor.encryptDocumentName(document);
        log.debug("content number = " + ver.getContentID());
        if (ver.getContentID()!=null && ver.getContentID().intValue()>0){
          DmsContent content = (DmsContent) dmsContentDAO.getObjectByID(ver.getContentID());
            //Update physical filename in storage location
          String oldConvertedName = content.getConvertedName();
          //if (!DmsDocument.FOLDER_TYPE.equals(document.getDocumentType())){
          String foldersDir = docRetrievalManager.getFoldersDirectories(document).toString();
          log.debug("parent FolderPath = " + foldersDir);
          File oldDocumentFile = new File(foldersDir + oldConvertedName);
          File newDocumentFile = new File(foldersDir + newConvertedName);
          log.debug("oldDocumentFile  = " + oldDocumentFile.getAbsolutePath());
          log.debug("newDocumentFile  = " + newDocumentFile.getAbsolutePath());
          if (oldDocumentFile.isFile()) {
            log.debug("oldDocumentFile  exists");
            if (!oldDocumentFile.renameTo(newDocumentFile)) {
              log.error("Rename file operation fail.");
                  throw new ApplicationException(DmsErrorConstant.RENAME_FILE_ERROR);
                }
            if (oldDocumentFile.exists()) {
              oldDocumentFile.delete();
            }
           }
            //}

            //Update DMS_CONTENT table; change the converted name
          content.setConvertedName(newConvertedName);
          dmsContentDAO.updateObject(content);

        }
      }
      //}
    }
  }
  
  
  public void minorCheckInRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws
    ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DocumentOperationManager docOperationManager = new DocumentOperationManager(sessionContainer, conn);

    InputStream inputStream = null;
    FormFile formFile = null;

    try {
      MaintDmsVersionForm versionForm = (MaintDmsVersionForm)form;
      log.debug("minorCheckinDocument checkin type = " + versionForm.getCheckinType());

      Integer documentID = TextUtility.parseIntegerObj(versionForm.getDocumentID());
      String rootID = versionForm.getRootID();
      String parentID = versionForm.getParentID();
      /*
       * joan.xiong add code for bug EIP-399 by 2006/09/25
       */
      request.setAttribute("rootID", rootID);
      request.setAttribute("parentID", parentID);
      /*
       * joan.xiong add code end
       */

      String checkinType = versionForm.getCheckinType();
      DmsVersion version = (DmsVersion)versionForm.getFormData();

      DmsVersion latestVersion = version;
      DmsVersionDAObject versionDAO = new DmsVersionDAObject(sessionContainer, conn);
      List versionList = versionDAO.getParentVersionsListByParentIDByDocumentID(new Integer(0), documentID); //first level
      if (versionList.size() > 0) {
        latestVersion = (DmsVersion)versionList.get(0);
      }
      if (latestVersion.getParentID().intValue() == 0){
        version.setParentID(latestVersion.getID());
      }else{
        version.setParentID(latestVersion.getParentID());
      }

      //When there is a new update for check-in
      if (!DmsOperationConstant.NO_UPDATE_CHECKIN.equals(checkinType)) {
        formFile = versionForm.getUploadFile();
        inputStream = formFile.getInputStream();
        version.setItemSize(new Integer(formFile.getFileSize()));
        version.setDocumentID(documentID);
        version.setCheckinFileName(formFile.getFileName());
      }

      version.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
      DmsVersion newVersion = null;
      VersionControlManager versionControlManager = new VersionControlManager(sessionContainer, conn);
      newVersion = versionControlManager.checkinDocument(true, checkinType, documentID, version, inputStream);
      this.deleteCheckinJob(documentID);
      if (newVersion != null) {
        versionForm.setID(newVersion.getID().toString());
        request.setAttribute("documentID", newVersion.getDocumentID().toString());
      }
      versionControlManager.release();
      docOperationManager.release();
      docRetrievalManager.release();
      versionDAO=null;
    } catch (IOException ioe) {
      log.error(ioe, ioe);
    }finally{
      conn=null;
    }
  }

  public void NoUpdateCheckInRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws
    ApplicationException {
    //Release the check-out status from Document, Version and CheckoutHistory object
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);

    MaintDmsVersionForm versionForm = (MaintDmsVersionForm)form;
    log.debug("noUpdateCheckin checkin type = " + versionForm.getCheckinType());

    Integer documentID = TextUtility.parseIntegerObj(versionForm.getDocumentID());
    String rootID = versionForm.getRootID();
    String parentID = versionForm.getParentID();
    /*
     * joan.xiong add code for bug EIP-399 by 2006/09/25
     */
    request.setAttribute("rootID", rootID);
    request.setAttribute("parentID", parentID);
    /*
     * joan.xiong add code end
     */

    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    String sCurFunctionCode = docRetrievalManager.getCurFunctionCode(docRetrievalManager.getDocument(documentID));
    if (SystemFunctionConstant.DMS_PUBLIC_FOLDER.equals(sCurFunctionCode)){
      VersionControlManager versionControlManager = new VersionControlManager(sessionContainer, conn);
      versionControlManager.unlockDocumentForNoUpdateCheckin(documentID);
      versionControlManager.release();
    }
    this.deleteCheckinJob(documentID);
    request.setAttribute("documentID", documentID.toString());
    try{sessionContainer=null;} catch (Exception e) { log.error(e, e); } finally { conn = null; }

  }

  public void checkOutRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws
    ApplicationException {
    MaintDmsVersionForm versionForm = (MaintDmsVersionForm)form;
    Integer documentID = request.getParameter("documentID") == null ? TextUtility.parseIntegerObj(versionForm.getDocumentID()) :
                         TextUtility.parseIntegerObj(request.getParameter("documentID"));
    String rootID = versionForm.getRootID();
    String parentID = versionForm.getParentID();
    log.debug("INSIDE checkouT!!!: " + rootID + " " + parentID + "document = " + documentID);
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);

    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    DmsDocument document = docRetrievalManager.getDocument(documentID);
    document.setCurFunctionCode(versionForm.getCurFunctionCode());
    if (DmsOperationConstant.LIST_PERSONAL_HOME.equals(versionForm.getCurFunctionCode())) {
      document.setCurFunctionCode(docRetrievalManager.getCurFunctionCode(document));
    }
    VersionControlManager versionControlManager = new VersionControlManager(sessionContainer, conn);
    versionControlManager.checkoutDocument(DmsVersion.EXCLUSIVE_LOCK, document);
    versionControlManager.release();
    request.setAttribute("documentID", documentID.toString());
    try{sessionContainer=null;} catch (Exception e) { log.error(e, e); } finally { conn = null; }

  }

  public void checkinStatusCheck(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws
    ApplicationException {
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    MaintDmsVersionForm versionForm = (MaintDmsVersionForm)form;
    //Integer documentID = TextUtility.parseIntegerObj(versionForm.getDocumentID());
    Integer documentID = request.getParameter("documentID") == null ? TextUtility.parseIntegerObj(versionForm.getDocumentID()) :
                         TextUtility.parseIntegerObj(request.getParameter("documentID"));
    
    DmsDocumentDAObject dmsDocumentDAObject = new DmsDocumentDAObject(sessionContainer,conn);        
    DmsDocument documentRoot = (DmsDocument)dmsDocumentDAObject.getObjectByID(documentID);
    
    String rootID = (Utility.isEmpty(versionForm.getRootID())?documentRoot.getRootID().toString():versionForm.getRootID());
    String parentID = (Utility.isEmpty(versionForm.getParentID())?documentRoot.getParentID().toString():versionForm.getParentID());
    //for reference file to trigger udf workflow
    DmsDocumentIndexDAObject dmsDocumentIndexDAO = new DmsDocumentIndexDAObject(sessionContainer,conn);
    DmsDocumentIndex dmsDocumentIndex = (DmsDocumentIndex)dmsDocumentIndexDAO.getIndexByDocID(documentID);
    if(!Utility.isEmpty(dmsDocumentIndex)){
      versionForm.setUserDefinedFieldID(dmsDocumentIndex.getUserDefinedFieldID().toString());
    }

    //String sCurFunctionCode = versionForm.getCurFunctionCode();
    String sCurFunctionCode = SystemFunctionConstant.DMS_PERSONAL_FOLDER;    
    
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer,conn); 
    DmsDocument rootDocument = docRetrievalManager.getRootFolderByRootID((documentRoot).getRootID());
    if (DmsOperationConstant.DMS_PERSONAL_ROOT.equals(rootDocument.getDocumentName())) {
      //For Personal Folder
    } else {
  	  sCurFunctionCode = SystemFunctionConstant.DMS_PUBLIC_FOLDER;
    }

    log.debug("check in status check =  " + documentID + " curFunctionCode= " + sCurFunctionCode);
    if (SystemFunctionConstant.DMS_PUBLIC_FOLDER.equals(sCurFunctionCode)) {
      if (documentID != null) {
        VersionControlManager versionControlManager = new VersionControlManager(sessionContainer, conn);
        boolean result = versionControlManager.isCurrentCheckoutPerson(documentID);
        if (!result) {
          throw new ApplicationException(DmsErrorConstant.DUPLICATE_FILE_CHECKOUT);
        }
        versionControlManager.release();
      }
    } else if (SystemFunctionConstant.DMS_EMPTY_FILE.equals(sCurFunctionCode)){
      versionForm.setCheckinType(DmsOperationConstant.CREATE_NEW_CHECKIN);
    }
    else {
      log.debug("personal folder check-in");
    }

    //Get reference no and description for display
    DmsDocument document = docRetrievalManager.getDocument(documentID);
    versionForm.setReferenceNo(document.getReferenceNo());
    versionForm.setDescription(document.getDescription());
    versionForm.setRootID(rootID);
    versionForm.setParentID(parentID);
    request.setAttribute("documentID", document.getID().toString());
    try{sessionContainer=null;} catch (Exception e) { log.error(e, e); } finally { conn = null; }

  }


  /** Parse the input */
  public void parseFormXmlDataToForm(MaintDmsVersionForm form ) throws IOException, SAXException {
    try { // Get an efficient reader for the file
      String odmaProcess = "" ;
      String opMode = "" ;
      String navMode="" ;
      String curFunctionCode = "" ;
      String closeFlag = "" ;
      String directPage ="" ;
      String documentID="" ;
      String parentID = ""  ;
      String rootID = "" ;
      String checkinType="" ;
      String referenceNo=""  ;
      String description="";     
      String trueFileName = "";      
      
      InputStream inputStream = null;
      FormFile formFile = null;
      formFile = form.getFormFieldXmlFile();
      //form.setUploadFile(formFile);
      inputStream = formFile.getInputStream();
      InputSource input = new InputSource();
      input.setByteStream(inputStream);      
      // Create an Document node as the root for the output.
      DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
      org.w3c.dom.Document indexFile = docBuilder.parse(input);

      /* Parse Document tag for the use name and login pwd */
      NodeList doclist = indexFile.getElementsByTagName("form");
      Node docNode = doclist.item(0);
      if (docNode != null) {
        if ("form".equals(docNode.getNodeName())) {
          try { odmaProcess = ((Element)docNode).getAttributeNode("odmaProcess").getValue(); } catch (Exception ignore) {}
          try { opMode = ((Element)docNode).getAttributeNode("opMode").getValue(); } catch (Exception ignore) {}
          try { navMode = ((Element)docNode).getAttributeNode("navMode").getValue(); } catch (Exception ignore) {}
          try { curFunctionCode = ((Element)docNode).getAttributeNode("curFunctionCode").getValue(); } catch (Exception ignore) {}
          try { closeFlag = ((Element)docNode).getAttributeNode("closeFlag").getValue(); } catch (Exception ignore) {}
          try { directPage = ((Element)docNode).getAttributeNode("directPage").getValue(); } catch (Exception ignore) {}
          try { documentID = ((Element)docNode).getAttributeNode("documentID").getValue(); } catch (Exception ignore) {}
          try { parentID = ((Element)docNode).getAttributeNode("parentID").getValue(); } catch (Exception ignore) {}
          try { rootID = ((Element)docNode).getAttributeNode("rootID").getValue(); } catch (Exception ignore) {}
          try { checkinType = ((Element)docNode).getAttributeNode("checkinType").getValue(); } catch (Exception ignore) {}
          try { referenceNo = ((Element)docNode).getAttributeNode("referenceNo").getValue(); } catch (Exception ignore) {}
          try { description = ((Element)docNode).getAttributeNode("description").getValue(); } catch (Exception ignore) {}
          try { trueFileName = ((Element)docNode).getAttributeNode("trueFileName").getValue(); } catch (Exception ignore) {}          

          if(!"".equals(opMode)){
            form.setOpMode(opMode);
          }
          if(!"".equals(navMode)){
            form.setNavMode(navMode);
          }
          if(!"".equals(curFunctionCode)){
            form.setCurFunctionCode(curFunctionCode);
          }
          if(!"".equals(closeFlag)){
            form.setCloseFlag(closeFlag);
          }
          if(!"".equals(directPage)){
            form.setDirectPage(directPage);
          }
          if(!"".equals(documentID)){
            form.setDocumentID(documentID);
          }
          if(!"".equals(parentID)){
            form.setParentID(parentID);
          }
          if(!"".equals(rootID)){
            form.setRootID(rootID);
          }
          if(!"".equals(checkinType)){
            form.setCheckinType(checkinType);
          }
          if(!"".equals(referenceNo)){
            form.setReferenceNo(referenceNo);
          }
          if(!"".equals(description)){
            form.setDescription(description);
          }          
          if(!"".equals(trueFileName)){
            form.setCheckinFileName(trueFileName);
          } 
          
        }
      }
    } catch (Exception e) {
      log.error(e, e);
    } finally{
        //input.close();        
    }
  }
  
  public void executeWorkflowRoutine(ActionMapping mapping, WorkflowActionFormInterface form, HttpServletRequest request, HttpServletResponse response, String opMode, String navMode) throws ApplicationException {
    log.info("########## MaintDmsDocumentDocumentAction Workflow Routine Begin ##########");
    MaintDmsVersionForm dmsDocumentForm = (MaintDmsVersionForm)form;
    SessionContainer sessionContainer = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    DmsDocumentDAObject dmsDocDAO = new DmsDocumentDAObject(sessionContainer, conn);
    WorkflowRecordDAObject workflowRecordDAO=new WorkflowRecordDAObject(sessionContainer,conn);
    Integer objID = TextUtility.parseIntegerObj(dmsDocumentForm.getDocumentID());
    
    DmsDocument dmsDocument=(DmsDocument)dmsDocDAO.getObjectByID(objID);
    
    String wfRecordIDs = form.getWorkflowRecordID();
    if(wfRecordIDs.indexOf("|") > 0){
      wfRecordIDs = wfRecordIDs.substring(0,wfRecordIDs.indexOf("|"));  
    }
    Integer workflowRecordID=TextUtility.parseIntegerObj(wfRecordIDs);
    
    WorkflowRecord workflowRecord=(WorkflowRecord)workflowRecordDAO.getObjectByID(workflowRecordID);
    String categoryID=workflowRecord.getWorkflowCategoryID().toString();
    
    if (GlobalConstant.TRUE.equals(form.getSubmitSystemWorkflow()) && !Utility.isEmpty(form.getWorkflowRecordID())) {
      //if (GlobalConstant.OP_MODE_INSERT.equals(opMode) || GlobalConstant.OP_MODE_INSERT_NEW.equals(opMode) ) {//
      //    || DmsOperationConstant.MOVE_OPERATION.equals(opMode) || DmsOperationConstant.COPY_OPERATION.equals(opMode)
        if(!(DmsDocument.PAPER_DOC_TYPE.equals(dmsDocument.getDocumentType()) && (SystemWorkflowConstant.DMS_CREATE_PAPER_DOCUMENT.equals(categoryID) || SystemWorkflowConstant.DMS_CREATE_PAPER_UDF_DOCUMENT.equals(categoryID)))){
          dmsDocDAO.updateStatusByObjectID(objID,GlobalConstant.RECORD_PENDING);
          dmsDocumentForm.setRecordStatus(GlobalConstant.RECORD_PENDING);
        }
      //}
    }
    dmsDocDAO=null;
    conn=null;
    log.info("########## MaintDmsDocumentDocumentAction Workflow Routine End   ##########");
  }
  
  /**
   * getObjectType
   *
   * @return  The corresponding object type of permission setup action.
   */
  
  public String getObjectType() {
    return(GlobalConstant.OBJECT_TYPE_DOCUMENT);
  }
  
  
  public void handleWorkflowRoutine(ActionMapping mapping, AbstractActionForm maintForm, HttpServletRequest request, HttpServletResponse response, String opMode, String navMode) throws ApplicationException {
    // Special Handling for Workflow.
    if (maintForm instanceof WorkflowActionFormInterface && this instanceof WorkflowActionInterface && GlobalConstant.TRUE.equals(((WorkflowActionFormInterface)maintForm).getSubmitSystemWorkflow())) {
      WorkflowActionFormInterface wfaForm = (WorkflowActionFormInterface)maintForm;

      // Start workflow track.
      WorkflowProgressManager wfProgressManager = new WorkflowProgressManager(this.getSessionContainer(request), this.getConnection(request));
      MaintWorkflowRecordForm recordForm = new MaintWorkflowRecordForm();
 
      if(WorkflowStep.DYNAMIC_ASSIGN_DUE_DATE_MANDATORY.equals(wfaForm.getNextStepAllowAssignDueDate()) ||
         WorkflowStep.DYNAMIC_ASSIGN_DUE_DATE_TRUE.equals(wfaForm.getNextStepAllowAssignDueDate())   ) {
        if (!Utility.isEmpty(wfaForm.getNextStepDueDates()) &&
            Utility.timestampToCalendar(TextUtility.parseDBDateTimeToTimeStamp(wfaForm.getNextStepDueDates()) ).before(Utility.timestampToCalendar(Utility.getCurrentTimestamp())) ){
          throw new ApplicationException(ErrorConstant.WORKFLOW_DUE_DATE_CANNOT_BE_LESS_THAN_CURRENT_DATE); 
        }
      }

      if(wfaForm.getWorkflowRecordID().indexOf("|") >0 ){
        recordForm.setID(wfaForm.getWorkflowRecordID().substring(0,wfaForm.getWorkflowRecordID().indexOf("|")));
      } else {
        recordForm.setID(wfaForm.getWorkflowRecordID());
      }
      if(maintForm instanceof com.dcivision.form.web.MaintFormSubmissionForm){
          com.dcivision.form.web.MaintFormSubmissionForm formSubmissionForm = (com.dcivision.form.web.MaintFormSubmissionForm)maintForm;
          recordForm.setObjParamMap(formSubmissionForm.getObjParamMap());
      }
      //bill add for EIP-1489
      DmsDocumentDAObject dmsDocumentDAO=new DmsDocumentDAObject(this.getSessionContainer(request),this.getConnection(request));
      MaintDmsVersionForm versionForm = (MaintDmsVersionForm)maintForm;
      DmsDocument dmsDocument = (DmsDocument)dmsDocumentDAO.getDocumentByID(new Integer(versionForm.getDocumentID()),DmsVersion.AVAILABLE_STATUS.toString());
      
      recordForm.setComment(wfaForm.getWorkflowComment());
      recordForm.setWorkflowObject(dmsDocument);
      recordForm.setFileNames(wfaForm.getFileNames());
      recordForm.setDmsFileNames(wfaForm.getDmsFileNames());
      recordForm.setNextStepDueDates(wfaForm.getNextStepDueDates());
      recordForm.setNextStepAllowAssignDueDate(wfaForm.getNextStepAllowAssignDueDate());
      recordForm.setTrackID(wfaForm.getTrackID());
        
      WorkflowProgress progress = (WorkflowProgress)wfProgressManager.startWorkflowTrack(recordForm);
      com.dcivision.customize.workflow.CustomizationForAction customization = new com.dcivision.customize.workflow.CustomizationForAction();
      customization.workflowSubmissionCustomization(this.getSessionContainer(request), this.getConnection(request), request, recordForm, progress);

      if(WorkflowProgress.FORM_EQUATION_ERROR.equals(wfProgressManager.getAutoRoutedToDefault())){
        this.addMessage(request, this.MESSAGE_FORM_EQUATION_HAS_ERROR);
      } else if (WorkflowProgress.ROUTED_TO_DEFAULT.equals(wfProgressManager.getAutoRoutedToDefault())){
        this.addMessage(request, this.MESSAGE_AUTO_ROUTED_TO_DEFAULT);
      }           
        
      request.setAttribute("assignStepMap", wfProgressManager.getAssignStepMap());
      if (progress!=null){
        request.setAttribute("WF_PROGRESS", progress);
        ((WorkflowActionInterface)this).executeWorkflowRoutine(mapping, wfaForm, request, response, opMode, navMode);
        this.addMessage(request, "workflow.label.workflow_submission_suffix",progress.getTrackID());
      }
    }
  }
  
  private void deleteCheckinJob(Integer documentID){
    try{
      Scheduler sched = SchedulerFactory.getScheduler();
      String[] triggerGroups;
      String[] triggers;
      String checkinTRIGGGERName = "CheckInExpirt_"+String.valueOf(documentID);
      
      triggerGroups = sched.getTriggerGroupNames();
      for (int i = 0; i < triggerGroups.length; i++) {
        triggers = sched.getTriggerNames(triggerGroups[i]);
        for (int j = 0; j < triggers.length; j++) {
          Trigger tg = sched.getTrigger(triggers[j], triggerGroups[i]);
          
          if (tg instanceof SimpleTrigger && tg.getName().equals(checkinTRIGGGERName)) {
            log.debug(" tg.getName() : "+tg.getName());
            log.debug(" emailSolutionHandleJobName : "+checkinTRIGGGERName);
            sched.unscheduleJob(checkinTRIGGGERName, triggerGroups[i]);
          }
        }
      } 
      
    }catch(Exception e){
      log.error(e, e);
    }
  }
}
